package com.kyzh.core.pager.weal.community

import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.gushenge.core.beans.PhotoBean
import com.gushenge.core.requests.AppRequest
import com.gushenge.core.toast
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.kyzh.core.R
import com.gushenge.core.base.activity.BaseActivity
import com.kyzh.core.databinding.ActCommunitypinglunBinding
import com.kyzh.core.pager.weal.community.adapter.ImageAdapter
import com.kyzh.core.pager.weal.community.viewmodel.CommunityViewModel
import com.kyzh.core.utils.GlideEngine
import com.kyzh.core.utils.vibrate

class CommunityPingLunActivity: BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Activity,id:String ) {
            val starter = Intent(context, CommunityPingLunActivity::class.java)
            starter.putExtra("id",id)
            context.startActivity(starter)
        }
    }
    private var photos :ArrayList<Photo> = arrayListOf()
    private val vm  by viewModels<CommunityViewModel>()
    private var photoBeans:ArrayList<PhotoBean> = arrayListOf()
    private val imgAdapter = ImageAdapter(photoBeans)
    private var progressDialog : ProgressDialog?= null
    private lateinit var db : ActCommunitypinglunBinding
    private var type  = 2
    private var id  = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db = DataBindingUtil.setContentView(this,R.layout.act_communitypinglun)
        id = intent.getStringExtra("id")!!
        showType()
        initView()
    }
    private fun initView() {
        progressDialog = ProgressDialog(this)

        db.rev.adapter = imgAdapter
        db.rev.layoutManager = GridLayoutManager(this,3)
        db.tag1.setOnClickListener {
            type = 2
            showType()
        }
        db.tag2 .setOnClickListener {
            type = 4
            showType()
        }
        photoBeans.add(PhotoBean("",true))

        imgAdapter.notifyDataSetChanged()
        imgAdapter.setOnItemChildClickListener{a,v,p->
            when(v.id){
                R.id.delect ->{
                    val photoBean = a.data  as ArrayList<PhotoBean>
                    var hasadd = false
                    photoBean.forEach {
                        if(  it.isAdd ){
                            hasadd = true
                        }
                    }
                    kotlin.runCatching {
                        if(!hasadd){
                            photos.removeAt(p)
                            photoBean.removeAt(p)
                            photoBean.add(8,PhotoBean("",true))
                            imgAdapter.notifyDataSetChanged()
                            vibrate(100)
                        }else{
                            photos.removeAt(p)
                            photoBean.removeAt(p)
                            imgAdapter.notifyDataSetChanged()
                            vibrate(100)
                        }
                    }
                }
                R.id.img ->{
                    val photoBean = a.data[p] as PhotoBean
                    if(photoBean.isAdd){
                        EasyPhotos.createAlbum(this,false,false, GlideEngine)
                            .complexSelector(true,1,9)
                            .setSelectedPhotos(photos)
                            .setVideo(true)
                            .setGif(false)
                            .start(object : SelectCallback() {
                                override fun onResult(photo: ArrayList<Photo>, isOriginal: Boolean) {
                                    photos.clear()
                                    photoBeans.clear()
                                    photos.addAll(photo)
                                    if(photos.size>=9){
                                        photos.forEach {
                                            photoBeans.add(PhotoBean(it.uri.toString()))
                                        }
                                    }else{
                                        photos.forEach {
                                            photoBeans.add(PhotoBean(it.uri.toString()))
                                        }
                                        photoBeans.add(PhotoBean("",true))
                                    }
                                    imgAdapter.notifyDataSetChanged()
                                }
                                override fun onCancel() {}
                            })
                    }
                }
            }
        }
        db.tvSubmit.setOnClickListener {
            // 数据校验
            val title = db.edtTitle.text.toString().trim()
            val context = db.edtContext.text.toString().trim()
            if(title.isNullOrBlank()){
                "请输入标题".toast()
                return@setOnClickListener
            }
            if(context.isNullOrBlank()){
                "请输入内容".toast()
                return@setOnClickListener
            }
            // 上传
            var currentImgurl = StringBuffer()
            var imgurl =""
            var index = 0
            if(imgAdapter.data.size>1){
                progressDialog?.setCancelable(false)
                progressDialog?.setMessage("上传中，请稍后..")
                progressDialog?.show()
                val arrayList = imgAdapter.data as ArrayList<PhotoBean>
                val size =if(imgAdapter.data.size ==9) 9 else imgAdapter.data.size-1
                arrayList.forEach {
                    if(!it.isAdd){
                        AppRequest.uploadImageOrVideo(this, Uri.parse(it.url)){
                            index++
                            progressDialog?.setMessage("上传进度${index}/${arrayList.size}，请等待")
                            if(this.isNotEmpty()){
                                currentImgurl.append(this).append(",")
                            }
                            if(index ==size){
                                progressDialog?.setMessage("提交中")
                                imgurl= currentImgurl.deleteCharAt(currentImgurl.length - 1).toString()
                                vm.subPingLun(type,id,title,context,imgurl){
                                    progressDialog?.dismiss()
                                    this.message.toast()
                                    if(this.code ==1){
                                        finish()
                                    }
                                }
                            }
                        }
                    }
                }
            }else{
                vm.subPingLun(type,id,title,context,imgurl){
                    this.message.toast()
                    if(this.code ==1){
                        finish()
                    }
                }
            }
        }
    }

    fun showType(){
        db.d = type
        when(type){
            2 ->{
                db.tag1.backgroundTintList = null
                db.tag2.backgroundTintList = ColorStateList.valueOf(Color.WHITE)
            }
            4 ->{
                db.tag1.backgroundTintList = ColorStateList.valueOf(Color.WHITE)
                db.tag2.backgroundTintList = null
            }
        }

    }
}